package com.duobaoyu.dby.supply.biz.strategy.message.delay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.duobaoyu.dby.channel.adapter.enums.biz.order.OrderStatusEnum;
import com.duobaoyu.dby.supply.biz.client.boundary.order.OrderBoundaryClient;
import com.duobaoyu.dby.supply.biz.client.boundary.order.bean.bo.OrderInfoBO;
import com.duobaoyu.dby.supply.biz.producer.message.OrderCancelMessage;
import com.duobaoyu.dby.supply.biz.service.order.OrderService;
import com.duobaoyu.dby.supply.biz.service.queue.core.DistributionQueueMessage;
import com.duobaoyu.dby.supply.biz.service.queue.service.AbstractDistributionQueueJobConsumer;
import com.duobaoyu.dby.supply.common.biz.bo.order.CancelOrderInBO;
import com.duobaoyu.dby.supply.common.biz.bo.order.CancelOrderOutBO;
import com.duobaoyu.dby.supply.common.biz.bo.order.OrderStatusCheckBO;
import com.duobaoyu.dby.supply.core.dinger.annotation.DingerTalk;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 延迟取消渠道订单
 * @author fengshaoyu
 * @version 1.0.0
 * @date 2023/10/12 15:26
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class DelayCancelChannelOrderDistributionQueueJobConsumer extends AbstractDistributionQueueJobConsumer {

	@Value("${delay.cancelChannelOrder.topicName}")
	private String topicName;

	private final OrderBoundaryClient orderBoundaryClient;
	private final OrderService orderService;

	@Override
	public String topicName() {
		return topicName;
	}

	@Override
	@DingerTalk(title = "取消渠道订单延迟消息")
	public void consume(DistributionQueueMessage distributionQueueMessage) {
		if(log.isDebugEnabled()) {
			log.debug("收到取消渠道订单消息: {}", JSON.toJSONString(distributionQueueMessage));
		}
		String data = distributionQueueMessage.getData();
		OrderCancelMessage orderCancelMessage = JSONObject.parseObject(data, OrderCancelMessage.class);
		OrderStatusCheckBO check = OrderStatusCheckBO.builder().orderSnList(orderCancelMessage.getOrderSnList())
				.checkStatusList(Lists.newArrayList(OrderStatusEnum.CANCEL.getValue()))
				.supplyTradeSn(orderCancelMessage.getSupplyTradeSn()).build();
		List<OrderInfoBO> orders = orderService.checkOrderStatus(check);
		List<CancelOrderInBO> orderCancelParamList = orders.stream().map(o -> CancelOrderInBO.builder()
				.orderSn(o.getOrderSn())
				.orderTradeSn(o.getOrderTradeSn())
				.orderStatus(orderCancelMessage.getCancelBeforeOrderStatus())
				.channelTradeOrderSn(o.getChannelTradeOrderSn())
				.cancelReason(o.getCancelReason())
				.channelCode(o.getChannelCode())
				.build()
		).collect(Collectors.toList());
		CancelOrderOutBO cancelOrderOut = orderBoundaryClient.batchCancelOrder(orderCancelParamList);
		log.info("取消渠道订单结果: {}", JSON.toJSONString(cancelOrderOut));
	}
}
